package com.idanchuang.component.just.web.filter;

import com.idanchuang.component.just.web.config.ComponentConfig;
import com.zoi7.component.core.base.BaseClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 统一web流量过滤
 */
@WebFilter(urlPatterns = "/*", asyncSupported = true)
public class StandardWebFilter extends BaseClass implements Filter {

    private final List<InnerWebFilter> filters = new ArrayList<>();

    @Autowired(required = false)
    public StandardWebFilter(ComponentConfig componentConfig) {
        this.filters.add(new FirstFilter());
        this.filters.add(new WebAccessFilter(componentConfig));
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        // 前置过滤
        for (InnerWebFilter filter : filters) {
            if (!filter.matchUrlPatterns(req)) {
                continue;
            }
            if (!filter.preFilter(req, res)) {
                return;
            }
        }
        if(req instanceof HttpServletRequest) {
            req =  new ContentCachingRequestWrapper((HttpServletRequest) req);
        }
        // 执行请求
        try {
            chain.doFilter(req, res);
        } finally {
            // 后置过滤
            for (int i = filters.size() - 1; i >= 0; i--) {
                InnerWebFilter filter = filters.get(i);
                if (!filter.matchUrlPatterns(req)) {
                    continue;
                }
                filter.postFilter(req, res);
            }
        }
    }

}
